package com.project.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;

@Component
@Aspect
public class ServiceProxy {
    private static SqlSessionFactory factory;
    static{
        try {
            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        SqlSession session = factory.openSession();
        //得到目标对象
        Object targetObj = joinPoint.getTarget();
        //得到目标对象的属性列表
        Field[] farray = targetObj.getClass().getDeclaredFields();
        for(Field f : farray){
            if(f.getType().isInterface() && f.getType().getName().endsWith("Mapper")){
                //得到Mapper对象
                Object mapperObj = session.getMapper(f.getType());
                f.setAccessible(true);
                f.set(targetObj, mapperObj);
            }
        }
        //执行目标方法
        Object returnObj = joinPoint.proceed();
        //提交事务，关闭session
        session.commit();
        session.close();
        return returnObj;
    }
}
